//-------------------------------------------------------------------
// 头文件
//-------------------------------------------------------------------

#include "ui/actions.h"
#include "my_actions.h"

//-------------------------------------------------------------------
// 当前支付场次
//-------------------------------------------------------------------

session_info *now_session_info = NULL;

//-------------------------------------------------------------------
// 私有函数
//-------------------------------------------------------------------

// 输入框置空
static void clear_all_textarea(void)
{
    lv_label_set_text_static(objects.member_center_account_info_label, "卡号：xxxxxx\n手机号：xxxxxxxxxxx\n身份证号：\nxxxxxxxxxxxxxxxxxxx\n余额：xx.xx￥");
    lv_textarea_set_text(objects.get_ticket_textarea, "");
    lv_textarea_set_text(objects.member_center_phone_num, "");
    lv_textarea_set_text(objects.member_center_id_card, "");
    lv_textarea_set_text(objects.member_center_member_id, "");
    lv_textarea_set_text(objects.member_center_recharge_amount, "");
    lv_textarea_set_text(objects.pay_screen_member_id, "");
}

//-------------------------------------------------------------------
// 页面跳转处理
//-------------------------------------------------------------------
static lv_obj_t *getLvglObjectFromIndex(int32_t index)
{
    if (index == -1)
    {
        return 0;
    }
    return ((lv_obj_t **)&objects)[index];
}
void loadScreen_with_anim(enum ScreensEnum screenId, lv_screen_load_anim_t anim)
{
    currentScreen = screenId - 1;
    lv_obj_t *screen = getLvglObjectFromIndex(currentScreen);
    lv_scr_load_anim(screen, anim, 300, 0, false);
}

void action_click_the_film_for_details(lv_event_t *e)
{
    // TODO: Implement action click_the_film_for_details here
    film_info *film = (film_info *)lv_event_get_user_data(e);

    lv_image_set_src(objects.film_details_image, film->film_big_photo);

    char score_str[10]; // 电影评分转换字符串
    sprintf(score_str, "%.1f", film->film_score);

    // 上映时间转换字符串
    struct tm *release_time = localtime(&film->film_release_time);
    char release_time_str[50];
    sprintf(release_time_str, "%04d年%02d月%02d日",
            release_time->tm_year + 1900,
            release_time->tm_mon + 1,
            release_time->tm_mday);

    // 电影时长转换字符串
    int hours = film->film_play_time / 60;
    int minutes = film->film_play_time % 60;
    char play_time_str[50];
    sprintf(play_time_str, "%02d小时%02d分", hours, minutes);

    lv_label_set_text_fmt(objects.film_details_label,
                          "电影名：%s\n电影评分：%s\n上映时间：%s\n电影时长：%s\n电影标签：%s", film->film_name,
                          score_str,
                          release_time_str,
                          play_time_str,
                          film->film_label);

    init_session_list(film->film_id);

    loadScreen_with_anim(SCREEN_ID_FILM_DETAILS_SCREEN, LV_SCR_LOAD_ANIM_FADE_ON);
}

void action_click_the_session_to_pay(lv_event_t *e)
{
    // TODO: Implement action click_the_session_to_pay here
    now_session_info = (session_info *)lv_event_get_user_data(e);
    // 打印当前场次信息
    printf("当前场次信息：\n"
           "电影ID：%ld\n"
           "影厅ID：%ld\n"
           "场次ID：%ld\n"
           "价格：%.2f\n",
           now_session_info->film_id,
           now_session_info->hall_id,
           now_session_info->session_id,
           now_session_info->session_price);
    loadScreen_with_anim(SCREEN_ID_PAY_SCREEN, LV_SCR_LOAD_ANIM_FADE_ON);
}

void action_go_get_ticket_screen(lv_event_t *e)
{
    // TODO: Implement action go_get_ticket_screen here
    loadScreen_with_anim(SCREEN_ID_GET_TICKET_SCREEN, LV_SCR_LOAD_ANIM_FADE_ON);
}

void action_go_buy_ticket_screen(lv_event_t *e)
{
    // TODO: Implement action go_buy_ticket_screen here
    loadScreen_with_anim(SCREEN_ID_BUY_TICKET_SCREEN, LV_SCR_LOAD_ANIM_FADE_ON);
}

void action_go_member_center_screen(lv_event_t *e)
{
    // TODO: Implement action go_member_center_screen here
    loadScreen_with_anim(SCREEN_ID_MEMBER_CENTER_SCREEN, LV_SCR_LOAD_ANIM_FADE_ON);
}

void action_return_main_screen(lv_event_t *e)
{
    // TODO: Implement action go_main_screen here
    clear_all_textarea();
    loadScreen_with_anim(SCREEN_ID_MAIN_SCREEN, LV_SCR_LOAD_ANIM_MOVE_RIGHT);
}

void action_return_buy_ticket_screen(lv_event_t *e)
{
    // TODO: Implement action return_buy_ticket_screen here
    loadScreen_with_anim(SCREEN_ID_BUY_TICKET_SCREEN, LV_SCR_LOAD_ANIM_MOVE_RIGHT);
}

void action_return_film_details_screen(lv_event_t *e)
{
    // TODO: Implement action return_film_details_screen here
    clear_all_textarea();
    loadScreen_with_anim(SCREEN_ID_FILM_DETAILS_SCREEN, LV_SCR_LOAD_ANIM_MOVE_RIGHT);
}

//-------------------------------------------------------------------
// 键盘控制
//-------------------------------------------------------------------

void action_show_get_ticket_key_board(lv_event_t *e)
{
    // TODO: Implement action show_get_ticket_key_board here
    set_var_hide_get_ticket_key_board(false);
}

void action_hide_get_ticket_key_board(lv_event_t *e)
{
    // TODO: Implement action hide_get_ticket_key_board here
    set_var_hide_get_ticket_key_board(true);
}

void action_show_member_center_key_board(lv_event_t *e)
{
    // TODO: Implement action show_member_center_key_board here
    lv_obj_t *ta = lv_event_get_target_obj(e);
    lv_keyboard_set_textarea(objects.member_center_key_board, ta); // 绑定输入框
    set_var_hide_member_center_key_board(false);
}

void action_hide_member_center_key_board(lv_event_t *e)
{
    // TODO: Implement action hide_member_center_key_board here
    set_var_hide_member_center_key_board(true);
}

void action_show_pay_screen_key_board(lv_event_t *e)
{
    // TODO: Implement action show_pay_screen_key_board here
    set_var_hide_pay_screen_key_board(false);
}

void action_hide_pay_screen_key_board(lv_event_t *e)
{
    // TODO: Implement action hide_pay_screen_key_board here
    set_var_hide_pay_screen_key_board(true);
}

//-------------------------------------------------------------------
// 取票事件
//-------------------------------------------------------------------

void action_get_a_ticket(lv_event_t *e)
{
    // TODO: Implement action get_a_ticket here
    char *num_str = lv_textarea_get_text(objects.get_ticket_textarea);
    uint32_t option = lv_roller_get_selected(objects.get_ticket_roller);
    bool get_flag = false;

    if (!list_empty(order_dcll_head))
    {
        order_dcll *pos; // 从后往前遍历
        list_for_each_entry_reverse(pos, order_dcll_head, list)
        {
            if (pos->order_info != NULL)
            {
                // 找到这个账号
                acc_dcll *acc_pos;
                list_for_each_entry(acc_pos, acc_dcll_head, list)
                {
                    // 判断数据内容是否为空
                    if (acc_pos->acc_info == NULL)
                    {
                        printf("<%s>[%d] 账号数据为空\n", __FILE__, __LINE__);
                        continue;
                    }

                    if (acc_pos->acc_info->acc_id == pos->order_info->acc_id)
                    { // 找到账号后，匹配取号信息

                        switch (option)
                        {
                        case 0: // 身份证号
                            if (strcmp(num_str, acc_pos->acc_info->acc_id_card) == 0)
                            {
                                printf("<%s>[%d] 身份证号匹配成功\n", __FILE__, __LINE__);
                                get_flag = true;
                            }
                            break;
                        case 1: // 电话号码
                            if (strcmp(num_str, acc_pos->acc_info->acc_phone) == 0)
                            {
                                printf("<%s>[%d] 电话号码匹配成功\n", __FILE__, __LINE__);
                                get_flag = true;
                            }
                            break;
                        case 2: // 会员编号
                        {
                            char tmp_str[7]; // 6位字符串 + '\0'
                            sprintf(tmp_str, "%06ld", acc_pos->acc_info->member_id);

                            if (strcmp(num_str, tmp_str) == 0)
                            {
                                printf("<%s>[%d] 会员编号匹配成功\n", __FILE__, __LINE__);
                                get_flag = true;
                            }

                            break;
                        }
                        case 3: // 购票编号
                        {
                            char tmp_str[17]; // 16位字符串 + '\0'
                            sprintf(tmp_str, "%016ld", pos->order_info->order_id);

                            if (strcmp(num_str, tmp_str) == 0)
                            {
                                printf("<%s>[%d] 购票编号匹配成功\n", __FILE__, __LINE__);
                                get_flag = true;
                            }

                            break;
                        }

                        default:
                            break;
                        }
                        break;
                    }
                }
            }
            if (get_flag)
            {
                break;
            }
        }
    }

    if (get_flag)
    {
        clear_all_textarea();
        printf("取票成功，打印票据中……\n");
    }
    else
    {
        printf("取票信息匹配失败！\n");
    }
}

//-------------------------------------------------------------------
// 注册事件
//-------------------------------------------------------------------

void action_register_a_member(lv_event_t *e)
{
    // TODO: Implement action register_a_member here

    char *tmp_phone = lv_textarea_get_text(objects.member_center_phone_num);
    char *tmp_id_card = lv_textarea_get_text(objects.member_center_id_card);

    // 检查电话号码格式
    if (strlen(tmp_phone) != 11)
    {
        printf("<%s>[%d] 电话号码格式错误\n", __FILE__, __LINE__);
        return;
    }

    // 检查身份证号格式
    if (strlen(tmp_id_card) != 18)
    {
        printf("<%s>[%d] 身份证号格式错误\n", __FILE__, __LINE__);
        return;
    }

    // 判断是否重复
    if (!list_empty(acc_dcll_head))
    {
        acc_dcll *pos; // 从后往前遍历
        list_for_each_entry_reverse(pos, acc_dcll_head, list)
        {
            if (strcmp(pos->acc_info->acc_phone, tmp_phone) == 0)
            {
                printf("<%s>[%d] 电话号码已存在\n", __FILE__, __LINE__);
                return;
            }
            if (strcmp(pos->acc_info->acc_id_card, tmp_id_card) == 0)
            {
                printf("<%s>[%d] 身份证号已存在\n", __FILE__, __LINE__);
                return;
            }
        }
    }

    uint32_t tmp_option = lv_dropdown_get_selected(objects.member_center_dropdown);

    ACC_TYPE option = -1;
    switch (tmp_option)
    {
    case 0:
        option = SUPER_MEMBERS;
        break;
    case 1:
        option = HIGH_LEVEL_MEMBERS;
        break;
    case 2:
        option = REGULAR_MEMBERS;
        break;
    }

    add_acc_node(tmp_phone, tmp_id_card, option);
}

//-------------------------------------------------------------------
// 余额操作
//-------------------------------------------------------------------

void action_inquiry_member_balance(lv_event_t *e)
{
    // TODO: Implement action inquiry_member_balance here

    char *tmp_id = lv_textarea_get_text(objects.member_center_member_id);

    // 判断是否存在卡号
    if (!list_empty(acc_dcll_head))
    {
        acc_dcll *pos; // 从后往前遍历
        list_for_each_entry_reverse(pos, acc_dcll_head, list)
        {
            char id_str[7]; // 6位字符串 + '\0'
            sprintf(id_str, "%06ld", pos->acc_info->member_id);
            if (strcmp(id_str, tmp_id) == 0)
            {
                char balance_str[10]; // 电影评分转换字符串
                sprintf(balance_str, "%.2f", pos->acc_info->acc_balance);
                lv_label_set_text_fmt(objects.member_center_account_info_label,
                                      "卡号：%s\n手机号：%s\n身份证号：\n%s\n余额：%s￥",
                                      id_str,
                                      pos->acc_info->acc_phone,
                                      pos->acc_info->acc_id_card,
                                      balance_str);
                return;
            }
        }
    }

    printf("该会员不存在！\n");
}

void action_recharge_member_balance(lv_event_t *e)
{
    // TODO: Implement action recharge_member_balance here
    char *tmp_id = lv_textarea_get_text(objects.member_center_member_id);
    char *tmp_amount = lv_textarea_get_text(objects.member_center_recharge_amount);

    // 判断金额字符串格式是否正确
    bool valid = true;
    int len = strlen(tmp_amount);
    int dot_count = 0;

    for (int i = 0; i < len; i++)
    {
        if (tmp_amount[i] == '.')
        {
            dot_count++;
            // 检查小数点位置是否合理
            if (i == 0 || i == len - 1 || dot_count > 1)
            {
                valid = false;
                break;
            }
        }
        else if (!isdigit(tmp_amount[i]))
        {
            valid = false;
            break;
        }
    }

    // 检查小数点后位数（可以没有小数点）
    if (valid && dot_count == 1)
    {
        char *dot_pos = strchr(tmp_amount, '.');
        if (strlen(dot_pos + 1) > 2)
        {
            valid = false;
        }
    }

    if (!valid)
    {
        printf("金额格式错误！\n");
        return;
    }

    // 判断是否存在卡号
    if (!list_empty(acc_dcll_head))
    {
        acc_dcll *pos; // 从后往前遍历
        list_for_each_entry_reverse(pos, acc_dcll_head, list)
        {
            // 转换金额为double形式，并加起来
            pos->acc_info->acc_balance += atof(tmp_amount);

            char id_str[7]; // 6位字符串 + '\0'
            sprintf(id_str, "%06ld", pos->acc_info->member_id);
            if (strcmp(id_str, tmp_id) == 0)
            {
                char balance_str[10]; // 电影评分转换字符串
                sprintf(balance_str, "%.2f", pos->acc_info->acc_balance);
                lv_label_set_text_fmt(objects.member_center_account_info_label,
                                      "卡号：%s\n手机号：%s\n身份证号：\n%s\n余额：%s￥",
                                      id_str,
                                      pos->acc_info->acc_phone,
                                      pos->acc_info->acc_id_card,
                                      balance_str);

                save_acc_node();
                return;
            }
        }
    }

    printf("该会员不存在！\n");
}

void action_pay_with_balance(lv_event_t *e)
{
    // TODO: Implement action pay_with_balance here

    char *tmp_id = lv_textarea_get_text(objects.pay_screen_member_id);

    // 判断是否存在卡号
    if (!list_empty(acc_dcll_head))
    {
        acc_dcll *pos; // 从后往前遍历
        list_for_each_entry_reverse(pos, acc_dcll_head, list)
        {
            char id_str[7]; // 6位字符串 + '\0'
            sprintf(id_str, "%06ld", pos->acc_info->member_id);
            if (strcmp(id_str, tmp_id) == 0)
            {
                // 得到单价
                double price = now_session_info->session_price;
                printf("单价：%.2lf\n", price);

                // 计算优惠
                double discount_price = 0;
                switch (pos->acc_info->acc_type)
                {
                case REGULAR_MEMBERS:
                    printf("【普通会员】0.95折\n");
                    discount_price = price * 0.95;
                    break;
                case HIGH_LEVEL_MEMBERS:
                    printf("【高级会员】0.90折\n");
                    discount_price = price * 0.9;
                    break;
                case SUPER_MEMBERS:
                    printf("【超级会员】0.80折\n");
                    discount_price = price * 0.8;
                    break;
                }
                printf("会员价：%.2lf\n", discount_price);

                // 判断余额是否足够
                if (pos->acc_info->acc_balance >= discount_price)
                {
                    pos->acc_info->acc_balance -= discount_price;
                    save_acc_node();
                    add_order_node(pos->acc_info->acc_id, now_session_info->session_id, discount_price);
                    printf("付款成功，余额：%.2lf\n", pos->acc_info->acc_balance);
                }
                else
                {
                    printf("余额<%.2f>不足，请充值！\n", pos->acc_info->acc_balance);
                }

                return;
            }
        }
    }

    printf("该会员不存在！\n");
}
